package com.situ.fly.controller;

import java.util.List;


import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import com.situ.fly.entity.Answer;
import com.situ.fly.entity.Question;
import com.situ.fly.entity.User;
import com.situ.fly.service.AnswerService;
import com.situ.fly.service.QuestionService;

/*
 *  处理与帖子相关的请求
 * 1、添加@Controller注解
 * 2、添加@RequestMapping注解
 * 3、添加具体的处理器方法
 */
@Controller
@RequestMapping("/jie")
public class JieController {

	@Autowired
	private QuestionService questionService;
	@Autowired
	private AnswerService answerService;
	/**
 * 访问发表帖子的页面
 * 
 * 
 */
	 @GetMapping("/add")
	public String add() {
		
		return "jie/add";
		
		
	}
	 /**
	  * 
	  * 处理发布帖子的请求
	  * 
	  * 
	  */
	 @PostMapping("/add")
	 public String add(Question question,String vercode,
			 HttpSession session,
			 Model model) {
		 //1、获取参数
		 //2、处理业务
		 String oldVercode=(String) session.getAttribute("vercode");
		 if (oldVercode==null||!vercode.toUpperCase().equals(oldVercode)) {
			
		
		 model.addAttribute("error","验证码错误！！");
		 return "jie/add";
		 }
		 //Filter过滤器
		 //三大核心 Servlet(jsp),Filter,Listener
		 //SpringMVC用拦截器完成用户统一认证
		 //获取当前登录用户的id
		 
		 User user=(User) session.getAttribute("user");
		 question.setUid(user.getId());
		 //调用service层
		 
		 int result=questionService.add(question);
		 
		 if (result>0) {
			//跳转到这个问题详情的页面
			 return "redirect:/jie/detail?id="+question.getId();
				
			 
		}else {
			//添加失败
			model.addAttribute("error","发布失败！！");
		}
		 return "jie/add";
		 
	 }
	 /**
	  * 
	  * 帖子详情
	  * 
	  */
	 @GetMapping("/detail")
	 public String detail(Integer id,Model model) {
		 //根据id查询出问题的全部信息
		 Object question=questionService.getById(id);
		 
		 
		 //并且通过、model带到模板中
		 model.addAttribute("question",question);
		 //根据问题id查询问题的回复
		 List  answers=answerService.getByQid(id);
		 
		 model.addAttribute("answers",answers);	
		 
		 
		 return "jie/detail";
		 
	 }
	 @PostMapping("reply")
	 public String reply(Answer answer,
			 HttpSession session,
			 Model model) {
		 //1、获取参数
		 //2、获取当前登录用户的id
		 User user=(User) session.getAttribute("user");
		 answer.setUid(user.getId());
		 //调用Service层
		 int result=answerService.add(answer);
		 return "redirect:/jie/detail?id=" + answer.getQid();
		 
	 }
}
